using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using ShopPowerTemplate.Entities;
using ShopPowerTemplate.IoC;
using ShopPowerTemplate.Presentation.Mvc.Extensions;
using ShopPowerTemplate.Presentation.Mvc.Models;
using ShopPowerTemplate.Presentation.Mvc.ViewModels;
using ShopPowerTemplate.Services;

namespace ShopPowerTemplate.Presentation.Mvc.Controllers
{
	public partial class OrderDetailControllerBase : BaseController
	{
		#region Members

        protected IOrderDetailService _orderDetailService;
        protected IOrderService _orderService;
        protected IProductDetailService _productDetailService;

        #endregion

        #region Constructors

        public OrderDetailControllerBase(IOrderDetailService orderDetailService, IOrderService orderService, IProductDetailService productDetailService)
        {
            _orderDetailService = orderDetailService;
            _orderService = orderService;
            _productDetailService = productDetailService;
        }	

        #endregion

		#region Index

		// **************************************
        // URL: /OrderDetail
        // **************************************
		public virtual ActionResult Index()
		{
			IndexOrderDetailViewModel viewModel = new IndexOrderDetailViewModel();
			ViewBag.PageIndex = this.GetPageIndex();
            ViewBag.PageSize = this.GetPageSize();
			ViewBag.SearchValue = this.GetSearchValue();
		
			return View(viewModel);
		}

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Load(string sidx, string sord, int page, int rows, string search, int mode = 1)
        {
            string searchValue = this.GetSearchValue();
            OrderBy orderBy = this.GetOrderBy();
            int pageIndex = this.GetPageIndex();
            int pageSize = this.GetPageSize();

            if (mode == (int)JQGridActionEnum.DefaultLoad)
            {                
                pageSize = (pageIndex + 1) * pageSize;
                pageIndex = 0;
            }
            else if (mode == (int)JQGridActionEnum.ShowMoreResults)
            {
                pageIndex = page;
                this.SetPageIndex(pageIndex);
            }
            else if (mode == (int)JQGridActionEnum.CustomSearch)
            {
                searchValue = search;
                this.SetSearchValue(searchValue);
                pageIndex = 0;
                this.SetPageIndex(pageIndex);
                orderBy = new OrderBy("", true);
                this.SetOrderBy(orderBy);
            }

            if (!string.IsNullOrEmpty(sidx)) // Sort request
            {
                orderBy = new OrderBy(sidx, sord == "asc");
                this.SetOrderBy(orderBy);
            }

            List<OrderDetail> searchList = _orderDetailService.Search(searchValue, orderBy.Property, orderBy.Ascending, pageIndex, pageSize);
            int count = _orderDetailService.SearchCount(searchValue);
            
			if (!string.IsNullOrEmpty(sidx)) // Sort request
            {
                pageIndex = this.GetPageIndex();
            }

            var data = new
            {
                total = Math.Ceiling((float)count/(float)pageSize),        // Total pages
                page = pageIndex,      // Current page
                records = count,  // Total records
                rows = from orderDetail in searchList     // Row data
                       select new
                       {
                           id = orderDetail.Id,                
                           cell = new string[] {
						   
                                orderDetail.Quantity.ToString(),
								orderDetail.Price.ToString(),
								orderDetail.Tax.ToString(),
								orderDetail.Discount.ToString(),
								orderDetail.Order != null ? orderDetail.Order.IdentityDescription : string.Empty,
								orderDetail.ProductDetail != null ? orderDetail.ProductDetail.IdentityDescription : string.Empty
								
                           }
                       }
            };

            return Json(data);
        }

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Delete(int id)
        {
            try
            {
                _orderDetailService.Remove(id);
            }
            catch (RemoveException ex)
            {
                Response.StatusCode = 500;
                return Content(ex.Message);
            }
            return Content(string.Empty);
        }
		
		public virtual FileContentResult Report()
        {
            IList<OrderDetail> _orderDetailList = _orderDetailService.Search(this.GetSearchValue());            
            StringBuilder strBuilder = new StringBuilder();

            // columns
            strBuilder.AppendLine("Quantity;Price;Tax;Discount;Order;ProductDetail");

            // rows
            foreach (OrderDetail orderDetail in _orderDetailList)
            {
                List<string> rowData = new List<string>() { orderDetail.Quantity.ToString(), orderDetail.Price.ToString(), orderDetail.Tax.ToString(), orderDetail.Discount.ToString(), orderDetail.Order != null ? orderDetail.Order.IdentityDescription : string.Empty, orderDetail.ProductDetail != null ? orderDetail.ProductDetail.IdentityDescription : string.Empty };
                strBuilder.AppendLine(rowData.Aggregate((x, y) => x + ";" + y));
            }

			// encode report content
            System.IO.MemoryStream content = new System.IO.MemoryStream();
            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(content, UTF8Encoding.UTF8))
                writer.Write(strBuilder.ToString());

            return File(content.ToArray(), "text/csv", "OrderDetail.csv");
        }
		

		#endregion

		#region Create

		// *******************************************
        // URL: /OrderDetail/Create
        // *******************************************
		[AcceptVerbs(HttpVerbs.Get)]
        public virtual ActionResult Create()
        {
            OrderDetail orderDetail = new OrderDetail();
            CreateOrderDetailViewModel viewModel = Mapper.Map<OrderDetail, CreateOrderDetailViewModel>(orderDetail);
            List<Order> allOrder = _orderService.FindAll();
            List<ProductDetail> allProductDetail = _productDetailService.FindAll();
            viewModel.OrderList = allOrder;
            viewModel.ProductDetailList = allProductDetail;
            
			return View(viewModel);
        }

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Create(CreateOrderDetailViewModel orderDetailModel)
        {
            if (ModelState.IsValid)
            {
                OrderDetail orderDetail = new OrderDetail();
                AutoMapper.Mapper.Map<CreateOrderDetailViewModel, OrderDetail>(orderDetailModel, orderDetail);
 

				_orderDetailService.Add(orderDetail);

                return RedirectToAction("Edit", new { id = orderDetail.Id});
            }
            else
            {
				List<Order> allOrder = _orderService.FindAll();
				List<ProductDetail> allProductDetail = _productDetailService.FindAll();
				orderDetailModel.OrderList = allOrder;
				orderDetailModel.ProductDetailList = allProductDetail;

                return View(orderDetailModel);
            }
		}
		

		#endregion

		#region Edit

		// *******************************************
        // URL: /OrderDetail/Edit/id
        // *******************************************
		[AcceptVerbs(HttpVerbs.Get)]
        public virtual ActionResult Edit(int id)
        {
            OrderDetail orderDetail = _orderDetailService.Find(id);
            EditOrderDetailViewModel viewModel = Mapper.Map<OrderDetail, EditOrderDetailViewModel>(orderDetail);
            List<Order> allOrder = _orderService.FindAll();
            List<ProductDetail> allProductDetail = _productDetailService.FindAll();
            viewModel.OrderList = allOrder;
            viewModel.ProductDetailList = allProductDetail;
            
			return View(viewModel);
        }

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Edit(EditOrderDetailViewModel orderDetailModel)
        {
            if (ModelState.IsValid)
            {
                OrderDetail orderDetail = _orderDetailService.Find(orderDetailModel.Id);
                AutoMapper.Mapper.Map<EditOrderDetailViewModel, OrderDetail>(orderDetailModel, orderDetail);
                
				_orderDetailService.Change(orderDetail);

                return RedirectToAction("Index");
            }
            else
            {
				List<Order> allOrder = _orderService.FindAll();
				List<ProductDetail> allProductDetail = _productDetailService.FindAll();
				orderDetailModel.OrderList = allOrder;
				orderDetailModel.ProductDetailList = allProductDetail;

                return View(orderDetailModel);
            }
		}
		

		#endregion

		#region Details

		// *******************************************
        // URL: /OrderDetail/Details/id
        // *******************************************
		[AcceptVerbs(HttpVerbs.Get)]
        public virtual ActionResult Details(int id)
        {
            OrderDetail orderDetail = _orderDetailService.Find(id);
            DetailsOrderDetailViewModel viewModel = Mapper.Map<OrderDetail, DetailsOrderDetailViewModel>(orderDetail);
            
			return View(viewModel);
        }
		

		#endregion
	}
}
